package com.msy.zk.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.msy.zk.ZkApplication;
import com.msy.zk.config.JdbcConfig;
import com.msy.zk.serilize.ZkStrSerializer;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Component
public class ConnectionUtil {

    public void zkClient() {
        ZkClient client = new ZkClient("linux121:2181,linux122:2181,linux123:2181");
        client.setZkSerializer(new ZkStrSerializer());
        String dir = "/datasource";
        client.subscribeDataChanges(dir, new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                System.out.println(s);
                System.out.println(o);
                readData(client, dir);
                System.out.println(s);

            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                try (final DruidDataSource datasoure = getDatasoure(client, dir)) {
                }
            }
        });
    }


    private void readData(ZkClient client, String dir) throws SQLException {
            DruidDataSource datasoure = getDatasoure(client, dir);
        try{
            DruidPooledConnection connection = datasoure.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement("select * from  user");
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                System.out.println("host:" + resultSet.getString(1) + "\tuser:" + resultSet.getString(2));
            }
        }catch (Exception e){
            System.out.println("failed");
            datasoure.close();
        }
    }

    private ZkClient initClient() {
        ZkClient client = new ZkClient("linux121:2181,linux122:2181,linux123:2181");
        client.setZkSerializer(new ZkStrSerializer());
        return client;
    }

    private DruidDataSource getDatasoure(ZkClient client, String dir) throws SQLException {
        JdbcConfig config = JSON.parseObject(client.readData(dir).toString(), JdbcConfig.class);
        DruidDataSource druid = new DruidDataSource();
        druid.setUrl(config.getUrl());
        druid.setDriverClassName(config.getDriverClass());
        druid.setUsername(config.getUsername());
        druid.setPassword(config.getPassword());
        druid.setConnectionErrorRetryAttempts(0);
        druid.setBreakAfterAcquireFailure(true);
        druid.setMaxWait(5000);
        return druid;
    }
}
